package com.example.hotel_lxy.ui.fragment;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.hotel_lxy.R;
import com.example.hotel_lxy.bean.BeanBean;
import com.example.hotel_lxy.bean.EventBusBean;
import com.example.hotel_lxy.bean.FMarketingBean;
import com.example.hotel_lxy.bean.ZeroSpSourceBean;
import com.example.hotel_lxy.net.Api;
import com.example.hotel_lxy.ui.activity.ChangePasswordActivity;
import com.example.hotel_lxy.ui.activity.CustomerActivity;
import com.example.hotel_lxy.ui.activity.DataActivity;
import com.example.hotel_lxy.ui.activity.LoginActivity;
import com.example.hotel_lxy.ui.activity.MainActivity;
import com.example.hotel_lxy.ui.activity.PotentialInformationActivity;
import com.example.hotel_lxy.ui.activity.RankingActivity;
import com.example.hotel_lxy.ui.activity.ReturnVisitActivity;
import com.example.hotel_lxy.ui.dialog.DialPhoneDialog;
import com.example.hotel_lxy.ui.main.CalendarActivity;
import com.example.hotel_lxy.utils.DatePhotoUtils;
import com.example.hotel_lxy.utils.DateUtils;
import com.example.hotel_lxy.utils.JurisdictionUtils;
import com.example.hotel_lxy.utils.SPUtils;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.ysxsoft.common_base.adapter.BaseQuickAdapter;
import com.ysxsoft.common_base.adapter.BaseViewHolder;
import com.ysxsoft.common_base.base.BaseFragment;
import com.ysxsoft.common_base.base.RBaseAdapter;
import com.ysxsoft.common_base.base.RViewHolder;
import com.ysxsoft.common_base.base.frame.list.IListAdapter;
import com.ysxsoft.common_base.base.frame.list.ListManager;
import com.ysxsoft.common_base.utils.JsonUtils;
import com.ysxsoft.common_base.utils.ToastUtils;
import com.ysxsoft.common_base.view.widgets.MultipleStatusView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/***
 *
 * 营销
 *
 */
public class FragmentMarketing extends BaseFragment implements IListAdapter<FMarketingBean.DataBean.ListBean> {

    @BindView(R.id.edit_search)
    EditText editSearch;
    @BindView(R.id.text_data)
    TextView textData;
    @BindView(R.id.text_ranking)
    TextView textRanking;
    @BindView(R.id.text_customer)
    TextView textCustomer;
    @BindView(R.id.text_courtesy)
    TextView textCourtesy;
    ListManager<FMarketingBean.DataBean.ListBean> manager;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.multipleStatusView)
    MultipleStatusView multipleStatusView;
    @BindView(R.id.smartRefresh)
    SmartRefreshLayout smartRefresh;
    @BindView(R.id.start_time)
    TextView startTime;
    @BindView(R.id.end_time)
    TextView endTime;
    @BindView(R.id.text_sp)
    TextView textSp;
    private PopupWindow mpopup_textSp;
    private List<String> mlist = new ArrayList<>();
    private String begin_time = "";
    private String end_time = "";
    private List<MpopupBean> mpopupList = new ArrayList<>();
    private String director_id = "";
    private String data_type;
    @Override
    public int getLayoutId() {
        return R.layout.fragment_marketing_activity;
    }

    String s;
    String s1;
    @Override
    protected void doWork(View view) {
        long timecurrentTimeMillis = new Date().getTime();
        String string = SPUtils.get(getContext(), "startTime", "").toString();
        String string1 = SPUtils.get(getContext(), "end_time", "").toString();
        if(string.equals("")){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
            begin_time = sdf.format(timecurrentTimeMillis);
            end_time = sdf.format(timecurrentTimeMillis);
            startTime.setText("" + begin_time);
            String[] split = end_time.split("-");
            if(split[1].substring(0,split[1].length()-1).equals("0")){
                int  u=Integer.valueOf(split[1].replace("0",""))+1;
                if(u<10){
                    s="0"+u;
                }else{
                    s=""+u;
                }
            }else{
                int  u=Integer.valueOf(split[1])+1;
                if(u<10){
                    s="0"+u;
                }else{
                    s=""+u;
                }
            }
            if(split[2].substring(0,split[2].length()-1).equals("0")){
                int  t= Integer.valueOf(split[2].replace("0",""))-1;
                if(t<10){
                    s1="0"+t;
                }else{
                    s1=""+t;
                }
            }else{
                int  t= Integer.valueOf(split[2])-1;
                if(t<10){
                    s1="0"+t;
                }else{
                    s1=""+t;
                }
            }
            end_time=split[0]+"-"+s+"-"+s1;
            endTime.setText("" + end_time);
            SPUtils.put(getContext(), "startTime", ""+begin_time);
            SPUtils.put(getContext(), "end_time", ""+end_time);
        }else{
            begin_time = string;
            end_time = string1;
            startTime.setText("" + string);
            endTime.setText("" + string1);
        }

        showDataView(view);
        editSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                request(1);
            }
        });

        editSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                return (event.getKeyCode() == KeyEvent.KEYCODE_ENTER);
            }
        });
    }

    private void showData(View view) {
        manager = new ListManager(this);
        manager.init(view);
        manager.getAdapter().setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

            }
        });
        manager.getAdapter().setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                request(manager.nextPage());
            }
        }, recyclerView);
        request(1);
    }

    private void showDataView(View view) {
        OkHttpUtils.post()
                .url(Api.POST_ZERO_VIEW)
                .addHeader("flag", SPUtils.get(getContext(), "token", "").toString())
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("TAG", "客户经理onError   " + e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("TAG", "客户经理onResponse   " + response);
                        BeanBean beanBean= JsonUtils.parseByGson(response, BeanBean.class);
                        if(beanBean.getCode().equals("4")){
                            SPUtils.put(getContext(),"token","");
                            Intent intent = new Intent(getContext(), LoginActivity.class).
                                    setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                            return;
                        }
                        ZeroSpSourceBean zeroSpSourceBean = JsonUtils.parseByGson(response, ZeroSpSourceBean.class);
                        if (zeroSpSourceBean.getCode().equals("0")) {
                            String string = SPUtils.get(getContext(), "id", "").toString();
                            List<ZeroSpSourceBean.DataBean.ListBean> list = zeroSpSourceBean.getData().getList();
                            MpopupBean mpopupBean1 = new MpopupBean();
                            mpopupBean1.setName("所有");
                            mpopupBean1.setId("");
                            mpopupList.add(mpopupBean1);
                            for (int i = 0; i < list.size(); i++) {
                                MpopupBean mpopupBean = new MpopupBean();
                                mpopupBean.setName(list.get(i).getUsername());
                                mpopupBean.setId(list.get(i).getId() + "");
                                mpopupList.add(mpopupBean);
                            }
                            for (int i = 0; i <mpopupList.size() ; i++) {
                                if(string.equals(""+mpopupList.get(i).getId())){
                                    director_id = mpopupList.get(i).getId() + "";
                                    textSp.setText("" + mpopupList.get(i).getName());
                                    break;
                                }
                            }
                            showData(view);
                        }
                    }
                });
    }

    @OnClick({R.id.text_data, R.id.text_ranking, R.id.text_customer, R.id.text_courtesy, R.id.start_time, R.id.end_time, R.id.text_sp})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.text_data://数据
                DataActivity.start();
                break;
            case R.id.text_ranking://排行榜
                boolean saytop = JurisdictionUtils.getSaytop(getContext());
                if(!saytop){
                    ToastUtils.longToast(getContext(),"当前账号没有操作权限哦");
                    return;
                }
                RankingActivity.start();
                break;
            case R.id.text_customer://客户
                CustomerActivity.start();
                break;
            case R.id.text_courtesy://彬彬有礼

                break;
            case R.id.start_time:
                data_type="1";
                CalendarActivity.start(3);
                break;
            case R.id.end_time:
                data_type="2";
                CalendarActivity.start(3);
                break;
            case R.id.text_sp:
                boolean ckqbyingxiao = JurisdictionUtils.getCkqbyingxiao(getContext());
                if(!ckqbyingxiao){
                    ToastUtils.longToast(getContext(),"当前账号没有操作权限哦");
                    return;
                }
                showPopwindowAllOffice();
                break;
        }
    }

    //全部 客户经理
    private void showPopwindowAllOffice() {

        View popview = getLayoutInflater().inflate(R.layout.item_popwindow, null);
        RecyclerView recyclerView = popview.findViewById(R.id.rv_pop_info);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        RBaseAdapter<MpopupBean> rBaseAdapterAllOffice = new RBaseAdapter<MpopupBean>(getContext(), R.layout.item_item_popwindow, mpopupList) {
            @Override
            protected void fillItem(RViewHolder holder, MpopupBean item, int position) {
                TextView text_title = holder.itemView.findViewById(R.id.text_title);
                text_title.setText(item.getName());
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        director_id = item.getId() + "";
                        textSp.setText("" + item.getName());
                        request(1);
                        mpopup_textSp.dismiss();
                    }
                });
            }

            @Override
            protected int getViewType(MpopupBean item, int position) {
                return 0;
            }
        };
        recyclerView.setAdapter(rBaseAdapterAllOffice);
        mpopup_textSp = new PopupWindow(popview,  240, ViewGroup.LayoutParams.WRAP_CONTENT);
        mpopup_textSp.setOutsideTouchable(true);
        mpopup_textSp.setFocusable(true);
        mpopup_textSp.showAsDropDown(textSp);
    }

    public static String hidePhone(Context context, String phone) {

        if (!TextUtils.isEmpty(phone) && phone.length() == 11) {

            phone = phone.substring(0, 3) + "****" + phone.substring(7, 11);

        } else {
            // Toast.makeText(context, "手机号格式不正确", Toast.LENGTH_SHORT).show();
        }
        return phone;

    }

    @Override
    public int getItemLayoutId() {
        return R.layout.item_marketing_adepter;
    }

    @Override
    public void request(int page) {
        String token = SPUtils.get(getContext(), "token", "").toString();
        OkHttpUtils.post()
                .url(Api.POST_MARKET_INDEX)
                .addHeader("flag", token)
                .addParams("begin_time", begin_time+"")
                .addParams("end_time", end_time+"")
                .addParams("director_id", ""+director_id)
                .addParams("search", ""+editSearch.getText().toString())
                .addParams("page",""+page)
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("TAG", "营销首页onError   " + e.getMessage());

                        manager.releaseRefresh();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        manager.releaseRefresh();
                        Log.e("TAG", "营销首页onResponse   " + response);
                        BeanBean beanBean= JsonUtils.parseByGson(response, BeanBean.class);
                        if(beanBean.getCode().equals("4")){
                            SPUtils.put(getContext(),"token","");
                            Intent intent = new Intent(getContext(), LoginActivity.class).
                                    setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                            return;
                        }
                        FMarketingBean fMarketingBean = JsonUtils.parseByGson(response, FMarketingBean.class);
                        if (fMarketingBean.getCode().equals("0")) {
                            if(page==1){
                                manager.resetPage();
                            }
                            manager.setData(fMarketingBean.getData().getList());
                            manager.getAdapter().notifyDataSetChanged();
                        }

                    }
                });
    }

    @Override
    public void fillView(BaseViewHolder helper, FMarketingBean.DataBean.ListBean s) {
        TextView book = helper.itemView.findViewById(R.id.text_book);
        TextView text_mobile = helper.itemView.findViewById(R.id.text_mobile);
        TextView text_returnvisit = helper.itemView.findViewById(R.id.text_returnvisit);
        TextView yu_time = helper.itemView.findViewById(R.id.yu_time);
        TextView text_mess = helper.itemView.findViewById(R.id.text_mess);
        TextView end_time=helper.itemView.findViewById(R.id.end_time);
        book.setText("" + s.getBook());
//        text_mobile.setText("" + hidePhone(getContext(), s.getMobile() + ""));
        text_mobile.setText(s.getMobile() + "");
        if(s.getIs_meeting().equals("1")){
            if (s.getBegin_night() == 1) {
                if(s.getEnd_night().equals("1")){
                    yu_time.setText("宴会时间：" + s.getYu_time() + " 上午 - "+s.getEnd_time()+" 上午");
                }else{
                    yu_time.setText("宴会时间：" + s.getYu_time() + " 上午 - "+s.getEnd_time()+" 下午");
                }
            } else {
                if(s.getEnd_night().equals("1")){
                    yu_time.setText("宴会时间：" + s.getYu_time() + " 下午 - "+s.getEnd_time()+" 上午");
                }else{
                    yu_time.setText("宴会时间：" + s.getYu_time() + " 下午 - "+s.getEnd_time()+" 下午");
                }
            }
        }else{
            if (s.getBegin_night() == 1) {
                yu_time.setText("宴会时间：" + s.getYu_time() + " 中午");
            } else {
                yu_time.setText("宴会时间：" + s.getYu_time() + " 晚上");
            }
        }
        text_mobile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (DatePhotoUtils.isPhone(s.getMobile() + "")) {
                    DialPhoneDialog.show(getContext(),null,s.getMobile()+"");
                } else {
                    com.luck.picture.lib.tools.ToastUtils.s(getContext(), "手机号有误");
                }
            }
        });
        end_time.setText("预订时间："+s.getAddtime());
        boolean sayvisitall = JurisdictionUtils.getSayvisitall(getContext());
        if(sayvisitall){
            text_returnvisit.setText("回访" + s.getCount() + "次");
        }else{
            boolean getuserid = JurisdictionUtils.getuserid(getContext(), s.getDirector_id());
            if(getuserid){
                text_returnvisit.setText("回访" + s.getCount() + "次");
            }else{
                text_returnvisit.setVisibility(View.GONE);
            }
        }

        text_mess.setText("宴会信息：" + s.getB_name() + "  " + s.getDname() + "  " + s.getDesk() + "桌");
        text_returnvisit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ReturnVisitActivity.start(s.getId() + "",""+director_id);
            }
        });
//

        helper.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(s.getYu_time()!=null||!s.getYu_time().equals("")){
                    String[] split = s.getYu_time().split("-");
                    PotentialInformationActivity.start(s.getBid() + "", split[0], split[1], split[2], s.getBegin_night() + "", s.getB_name());
                }
            }
        });
    }

    @Override
    public void fillMuteView(BaseViewHolder helper, FMarketingBean.DataBean.ListBean s) {

    }

    @Override
    public void attachActivity(AppCompatActivity activity) {

    }

    @Override
    public void dettachActivity() {

    }

    @Override
    public RecyclerView.LayoutManager getLayoutManager() {
        return new LinearLayoutManager(getContext());
    }

    @Override
    public boolean isMuteAdapter() {
        return false;
    }

    @Override
    public int[] getMuteTypes() {
        return new int[0];
    }

    @Override
    public int[] getMuteLayouts() {
        return new int[0];
    }


    // 普通事件的处理
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleEvent(EventBusBean carrier) {
        Log.e("tag",carrier.getStarttime()+"  123");
        if (carrier != null) {
            if(data_type==null){
                return;
            }
            if(data_type.equals("1")){
                startTime.setText("" + carrier.getStarttime());
            }else {
                endTime.setText("" + carrier.getStarttime());
            }
            begin_time =startTime.getText().toString();
            end_time = endTime.getText().toString();
            SPUtils.put(getContext(), "startTime", ""+begin_time);
            SPUtils.put(getContext(), "end_time", ""+end_time);

            request(1);
        }
    }




    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);  //事件的注册
    }



    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            if (EventBus.getDefault().isRegistered(this)) {
                EventBus.getDefault().unregister(this); //解除注册
            }
        } else {
            request(1);
            if (EventBus.getDefault().isRegistered(this)) {
                EventBus.getDefault().unregister(this); //解除注册
                EventBus.getDefault().register(this);  //事件的注册
            } else {
                EventBus.getDefault().register(this); //解除注册
            }
        }
    }

    public class MpopupBean {
        private String name;
        private String id;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }
    }
}